<template>
  <div>
    <!-- <ul>
      <li
        v-for="(row, i) in tableData"
        :key="row.__id__"
      >
        {{ row }}
      </li>
    </ul>
    columns: {{ columns }} -->
    <Row
      ref="tableRow"
      v-for="(row, i) in tableData"
      :key="row.__id__"
      v-model:value="tableData[i]"
      :index="i"
      :columns="columns"
      @add="handleAdd"
      @copy="handleCopy"
      @remove="handleReomve"
    >
      <slot
        :row="tableData[i]"
        :index="i"
      ></slot>
    </Row>

    <slot
      name="footer"
      :data="getTableData()"
    >
    </slot>
  </div>
</template>

<script lang="ts" setup>
import { ref, unref, nextTick } from "vue";
import { useTableData } from "./useTableData";
import type { Columns, WithTableSignal } from "./types";

import Row from "./Row.vue";

interface ChangeEvent {
  row: any;
  index: number;
  data: any[];
}

defineOptions({ name: "XRow" });

/**
 * Table's column setup
 */
const $props = defineProps<{
  columns: Columns<any>;
  raw: any;
}>();

/**
 * event for update Table's data
 */
const $emit = defineEmits<{
  (e: "change", { row, index, data }: ChangeEvent): void;
}>();

type Item = {
  [key: string | number]: any;
};

const { setTableData, getTableData, add, copy, remove, setAllState } =
  useTableData<Item>();

const tableData = setTableData([]);
const tableRow = ref<Item[]>([]);

/**
 * set & get Table's Data
 */
function setData(data: Item[]) {
  tableData.value = setTableData(data).value;
}
function getData() {
  return getTableData();
}

/**
 * Table evnet: "handleAdd", "handleCopy", "handleDelete"
 */
function handleAdd() {
  add(JSON.parse(JSON.stringify($props.raw)));
}

const handleCopy = (index: number) => {
  copy(index);
};
const handleReomve = (index: number) => {
  remove(index);
};

defineExpose({
  setData,
  getData,
  addData: handleAdd,
  setState: setAllState,
});
</script>
